package server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author junbao
 * 封装Response对象，需要依赖于OutputStream
 * 该对象需要提供核⼼⽅法，输出html
 */
public class Response {

    private OutputStream outputStream;

    public Response() {
    }

    public void output(String content) throws IOException {
        outputStream.write(content.getBytes());
    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    /**
     * 根据url获取到静态资源的绝对路径，通过输出流输出
     * @param path
     */
    public void outputHtml(String path, String serverPath) throws IOException {

       // 获取静态资源的绝对路径
        String absoluteResourcePath = StaticResourceUtil.getAbsolutePath(path);

        // 输入静态资源文件
        File file = new File(absoluteResourcePath);
        if(!file.exists()) {
            file = new File(serverPath + path);
        }
        if(file.exists() && file.isFile()) {
            // 输出静态资源
            StaticResourceUtil.outputStaticResource(new FileInputStream(file), outputStream);
        }else {
            // 输出404
            output(HttpProtocolUtil.getHttpHeader404());
        }
    }

}
